import flask
import math

app = flask.Flask(__name__, static_folder="images")

# 每页显示的电影条数
PAGE_SIZE = 5

@app.route("/")
def show():
    # 1️⃣ 读取全部电影数据 ---------------------------------------------------
    movies_raw = []
    try:
        with open("movies.csv", "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if line:                           # 跳过空行
                    movies_raw.append(line)
    except Exception as err:
        print("❌ 无法读取 movies.csv：", err)

    total_rows = len(movies_raw)
    # 如果没有数据，也给一个默认空页
    if total_rows == 0:
        page_count = 1
    else:
        page_count = math.ceil(total_rows / PAGE_SIZE)

    # 2️⃣ 解析当前页码 -------------------------------------------------------
    page_index = int(flask.request.values.get("pageIndex", 1))
    # 页码越界保护
    page_index = max(1, min(page_index, page_count))

    # 3️⃣ 取出该页对应的切片数据 --------------------------------------------
    start_row = (page_index - 1) * PAGE_SIZE
    end_row   = start_row + PAGE_SIZE
    page_rows = movies_raw[start_row:end_row]

    # 4️⃣ 构造传递给模板的 movies 列表 --------------------------------------
    movies = []
    for row in page_rows:
        # CSV: ID,imgName,title
        try:
            mid, img_name, title = row.split(",", 2)
        except ValueError:
            # 行格式不正确，跳过
            continue
        movies.append({
            "ID": mid.strip(),
            "mImage": img_name.strip(),
            "mTitle": title.strip()
        })

    # 5️⃣ 渲染模板 -----------------------------------------------------------
    return flask.render_template(
        "movie.html",
        movies=movies,
        pageIndex=page_index,
        pageCount=page_count
    )

if __name__ == "__main__":
    app.run(debug=True)
